from PySide6.QtCore import Qt, Signal
from qfluentwidgets import SettingCard, FluentIconBase, EditableComboBox
from app.common.config import cfg

class ComboBoxSettingCard(SettingCard):
    """ 可编辑下拉框设置卡片 """
    
    valueChanged = Signal(str)

    def __init__(self, icon: FluentIconBase, title: str, content: str, 
                 configItem, items=None, parent=None):
        """
        Parameters
        ----------
        icon: FluentIconBase
            卡片图标
        title: str
            卡片标题
        content: str
            卡片内容描述
        configItem: ConfigItem
            配置项
        items: list
            下拉框选项列表
        parent: QWidget
            父组件
        """
        super().__init__(icon, title, content, parent)
        self.configItem = configItem
        # 处理配置项值，移除括号及其内容

        
        # 创建可编辑下拉框
        self.comboBox = EditableComboBox(self)
        self.comboBox.setText(self.configItem.value)
        self.comboBox.setMinimumWidth(200)
        
        # 添加下拉选项
        if items:
            self.comboBox.addItems(items)
        
        # 将下拉框添加到右侧
        self.hBoxLayout.addWidget(self.comboBox, 0, Qt.AlignRight)
        self.comboBox.textChanged.connect(self._onValueChanged)

    def _onValueChanged(self, text: str):
        """ 值改变时的处理 """
        # 将\n转换为unicode转义,其他字符保持不变
        text_with_escaped_newlines = text.replace('\n', '\\n').replace('\r', '\\r')
        self.configItem.value = text_with_escaped_newlines
        cfg.save()
        self.valueChanged.emit(text_with_escaped_newlines)

    def getValue(self):
        """ 获取当前值 """
        return self.comboBox.text()

    def setValue(self, value: str):
        """ 设置值 """
        self.comboBox.setText(value)
        
    def setItems(self, items: list):
        """ 设置下拉选项 """
        self.comboBox.clear()
        self.comboBox.addItems(items) 